<template>
  <!-- 搜索区域 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="所属知识库">
        <el-input :model-value="knowledge?.name" :disabled="true" class="!w-360px" />
      </el-form-item>
      <el-form-item label="文档名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入文档名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择是否启用"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in common_enable_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button type="primary" plain @click="handleCreate" v-hasPermi="['ai:knowledge:create']">
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表区域 -->
  <ContentWrap>
    <el-table v-loading="listLoading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" prop="id" width="100" />
      <!--      <el-table-column label="知识库编号" prop="knowledgeId" />-->
      <el-table-column label="文档名称" prop="name" />
      <!--      <el-table-column label="文件 URL" prop="url" />-->
      <!--      <el-table-column label="内容" prop="content" />-->
      <el-table-column label="字符数" prop="contentLength" width="130" />
      <el-table-column label="token 数量" prop="tokens" width="130" />
      <el-table-column label="分片最大 Token 数" prop="segmentMaxTokens" width="150" />
      <el-table-column label="召回次数" prop="retrievalCount" width="130" />
      <el-table-column label="是否启用" prop="status" width="130">
        <template #default="scope">
          <!--          <dict-tag :options="common_enable_status" :value="scope.row.status" />-->
          <el-switch
            v-model="scope.row.status"
            :active-value="EnableStatusEnum.Enabled"
            :inactive-value="EnableStatusEnum.Disabled"
            @change="handleStatusChange(scope.row)"
            :disabled="!hasPermi('ai:knowledge:update')"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180px" />
      <el-table-column label="操作" width="180px" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row.id)"
            v-hasPermi="['ai:knowledge:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleSegment(scope.row.id)"
            v-hasPermi="['ai:knowledge:query']"
          >
            分段
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['ai:knowledge:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import { KnowledgeDocumentApi, KnowledgeDocumentVO } from '@/api/ai/knowledge/document'
import { KnowledgeApi, KnowledgeVO } from '@/api/ai/knowledge/knowledge'
import { useTagsView } from '@/hooks/web/useTagsView'
import { EnableStatusEnum } from '@/utils/constants'
import { hasPermi } from '@/utils/perm'

/** AI 知识库文档 列表 */
defineOptions({ name: 'AiKnowledgeDocument' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const route = useRoute() // 路由
const router = useRouter() // 路由
const tagsView = useTagsView()
const { common_enable_status } = useIntDict(DICT_TYPE.common_enable_status)

const listLoading = ref(true) // 列表的加载中状态
const list = ref<KnowledgeDocumentVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  knowledgeId: undefined,
  name: undefined,
  status: undefined,
  pageNo: 1,
  pageSize: 10
})
const queryFormRef = ref() // 搜索的表单
const knowledge = ref<KnowledgeVO>()

/** 查询列表 */
const getList = async () => {
  listLoading.value = true
  try {
    const data = await KnowledgeDocumentApi.getKnowledgeDocumentPage(queryParams)
    list.value = data.content
    total.value = data.totalElement
  } finally {
    listLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 跳转到创建文档页面 */
const handleCreate = () => {
  router.push({
    name: 'AiKnowledgeDocumentCreate',
    query: { knowledgeId: queryParams.knowledgeId }
  })
}

/** 跳转到更新文档页面 */
const handleUpdate = (id: number) => {
  router.push({
    name: 'AiKnowledgeDocumentUpdate',
    query: { id, knowledgeId: queryParams.knowledgeId }
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 弹出确认框
    await message.delConfirm()
    // 发起删除请求
    await KnowledgeDocumentApi.deleteKnowledgeDocument(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 修改状态操作 */
const handleStatusChange = async (row: KnowledgeDocumentVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === EnableStatusEnum.Enabled ? '启用' : '禁用'
    await message.confirm('确认要"' + text + '""' + row.name + '"文档吗?')
    // 发起修改状态
    await KnowledgeDocumentApi.updateKnowledgeDocumentStatus(row.id, row.status)
    message.success(t('common.updateSuccess'))
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === EnableStatusEnum.Enabled ? EnableStatusEnum.Disabled : EnableStatusEnum.Enabled
  }
}

/** 跳转到知识库分段页面 */
const handleSegment = (id: number) => {
  router.push({
    name: 'AiKnowledgeSegment',
    query: { documentId: id }
  })
}

const firstLoad = ref(true)
onActivated(() => {
  // keepalive组件才会启用，首次装载会在onMounted之后执行，后续从keepalive中被激活也会执行
  if (firstLoad.value) {
    // 确保不与onMounted重复执行逻辑
    firstLoad.value = false
    return
  }
  if (history.state?.reload) {
    getList()
  }
})

/** 初始化 **/
onMounted(async () => {
  queryParams.knowledgeId = route.query.knowledgeId as any
  if (!queryParams.knowledgeId) {
    message.error('知识库ID不存在，无法查看文档列表')
    tagsView.closeCurrent()
    router.push({ name: 'AiKnowledge' })
    return
  }
  knowledge.value = await KnowledgeApi.getKnowledge(queryParams.knowledgeId)
  getList()
})
</script>

<style scoped lang="scss"></style>
